package com.hzcx.app.simplechat.ui.moment.fragment;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hzcx.app.simplechat.R;
import com.hzcx.app.simplechat.base.BaseFragment;
import com.hzcx.app.simplechat.bean.UpLoadImgBean;
import com.hzcx.app.simplechat.chat.ChatUtil;
import com.hzcx.app.simplechat.chat.constant.ChatConstant;
import com.hzcx.app.simplechat.common.Common;
import com.hzcx.app.simplechat.ui.chat.ChatShareUserActivity;
import com.hzcx.app.simplechat.ui.chat.event.ChatShareUserEvent;
import com.hzcx.app.simplechat.ui.friend.event.DeleteFriendEvent;
import com.hzcx.app.simplechat.ui.home.AddFriendActivity;
import com.hzcx.app.simplechat.ui.main.MainActivity;
import com.hzcx.app.simplechat.ui.mine.MineUserInfoActivity;
import com.hzcx.app.simplechat.ui.moment.MomentInfoActivity;
import com.hzcx.app.simplechat.ui.moment.adapter.MomentAdapter;
import com.hzcx.app.simplechat.ui.moment.bean.MomentBean;
import com.hzcx.app.simplechat.ui.moment.contract.UserMomentContract;
import com.hzcx.app.simplechat.ui.moment.presenter.UserMomentPresenter;
import com.hzcx.app.simplechat.ui.publicui.CaptureResultActivity;
import com.hzcx.app.simplechat.ui.publicui.PublicRoundDialog;
import com.hzcx.app.simplechat.ui.publicui.WebViewActivity;
import com.hzcx.app.simplechat.ui.user.UserInfoActivity;
import com.hzcx.app.simplechat.ui.user.UserMomentActivity;
import com.hzcx.app.simplechat.ui.user.bean.UserInfoBean;
import com.hzcx.app.simplechat.ui.user.enums.SexEnum;
import com.hzcx.app.simplechat.ui.user.event.UserRemarkEvent;
import com.hzcx.app.simplechat.util.TextHttpUtil;
import com.hzcx.app.simplechat.util.UserInfoUtil;
import com.hzcx.app.simplechat.util.down.DownLoadUtil;
import com.hzcx.app.simplechat.util.dp.DpUtils;
import com.hzcx.app.simplechat.util.empty.EmptyUtils;
import com.hzcx.app.simplechat.util.glide.GlideUtils;
import com.hzcx.app.simplechat.util.image.ImageUtil;
import com.hzcx.app.simplechat.util.log.LogUtils;
import com.hzcx.app.simplechat.util.qrcode.QRCodeParseUtils;
import com.hzcx.app.simplechat.util.toast.ToastUtils;
import com.hzcx.app.simplechat.view.autogridview.PhotoLoader;
import com.hzcx.app.simplechat.view.autogridview.PhotoProgressUi;
import com.hzcx.app.simplechat.view.imageview.RoundImageView;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import indi.liyi.viewer.ImageViewer;
import indi.liyi.viewer.listener.OnItemLongPressListener;
import kr.co.namee.permissiongen.PermissionFail;
import kr.co.namee.permissiongen.PermissionGen;
import kr.co.namee.permissiongen.PermissionSuccess;

/**
 * 用户朋友圈
 */
public class UserMomentFragment extends BaseFragment<UserMomentPresenter> implements MomentAdapter.OnItemClickCallback,
        BaseQuickAdapter.OnItemClickListener, BaseQuickAdapter.OnItemChildClickListener, UserMomentContract.View, OnRefreshListener,
        BaseQuickAdapter.RequestLoadMoreListener {
    @BindView(R.id.rv_moment)
    RecyclerView rvMoment;
    @BindView(R.id.smart_refresh)
    SmartRefreshLayout smartRefresh;
    @BindView(R.id.view_top)
    View viewTop;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.imageViewer)
    public ImageViewer imageViewer;
    @BindView(R.id.ll_null)
    LinearLayout llNull;

    private List<MomentBean> momentData;
    private MomentAdapter momentAdapter;

    private int scrollY = 0;
    private int scrollHeight; // 透明度变化，距离顶部的高度
    private View headerView;

    private TextView tv_new_msg; //新消息

    private UserInfoBean userInfoBean;

    private RoundImageView ivHead;
    private TextView tvNickName;
    private ImageView ivSex;
    private TextView tvSign;
    private ImageView ivMomentBg;

    private int page = 1;
    private boolean isRefresh = true;

    private ImageView saveImageView;
    private String collectImgPath;

    @Override
    public int getLayout() {
        return R.layout.fragment_user_moment;
    }

    @Override
    public void initPresenter() {
        mPresenter = new UserMomentPresenter();
    }

    @Override
    public void initView() {
        momentData = new ArrayList<>();
        momentAdapter = new MomentAdapter(momentData);
        rvMoment.setLayoutManager(new LinearLayoutManager(getActivity(), RecyclerView.VERTICAL, false));
        rvMoment.setAdapter(momentAdapter);

        momentAdapter.setOnItemClickCallback(this);
        momentAdapter.setOnItemClickListener(this);
        momentAdapter.setOnItemChildClickListener(this);

        // 设置背景先透明
        viewTop.getBackground().mutate().setAlpha(0);

        scrollHeight = DpUtils.dp2px(getActivity(), 110);

        imageViewer.imageLoader(new PhotoLoader());

        smartRefresh.setOnRefreshListener(this);
        momentAdapter.setOnLoadMoreListener(this);
    }

    @Override
    public void initData() {

        userInfoBean = (UserInfoBean) getArguments().getSerializable(UserMomentActivity.INTENT_USER_INFO);

        addHeaderView();

        // 设置滑动监听，计算距离
        rvMoment.setOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                scorllTopView(dy);
            }
        });

//        smartRefresh.autoRefresh();
        mPresenter.getMomentList(getActivity(), userInfoBean.getMember_id(), page);
    }

    /**
     * 顶部标题透明度变化
     */
    private void scorllTopView(int dy) {
        scrollY += dy;
        int alpha = scrollY - scrollHeight;
        if (alpha <= 0) {
            alpha = 0;
        }
        if (scrollY - scrollHeight <= 255 && scrollY - scrollHeight >= 0) {
            // 先把顶部标题及按钮透明度消减为0
            tvTitle.setTextColor(Color.argb(255 - alpha, 255, 255, 255));
            ivBack.setImageAlpha(255 - alpha);
            ivBack.setImageResource(R.mipmap.ic_icon_back_white);
        } else if (scrollY - scrollHeight > 255) {
            // 顶部标题及按钮已经透明，改为黑色，并且逐渐显示头部背景
            tvTitle.setTextColor(getResources().getColor(R.color.color_282F3E));
            ivBack.setImageResource(R.mipmap.ic_icon_back_black);
            int num = alpha - 255;
            if (num >= 255) {
                num = 255;
            }
            tvTitle.setTextColor(Color.argb(num, 40, 47, 62));
            ivBack.setImageAlpha(num);
            viewTop.getBackground().mutate().setAlpha(num);
        } else {
            // 表示在最上面了，直接设置成初始状态
            tvTitle.setTextColor(getResources().getColor(R.color.color_white));
            ivBack.setImageResource(R.mipmap.ic_icon_back_white);
            tvTitle.setAlpha(1f);
            ivBack.setImageAlpha(255);
            viewTop.getBackground().mutate().setAlpha(0);
        }
    }

    /**
     * 查看大图
     *
     * @param position
     * @param list
     * @param viewGroup
     */
    @Override
    public void onItemClick(int position, List<String> list, ViewGroup viewGroup) {
        try {
            imageViewer.overlayStatusBar(true)
                    .imageData(list)
                    .bindViewGroup(viewGroup)
                    .loadProgressUI(new PhotoProgressUi())
                    .setOnItemLongPressListener((position1, imageView) -> {
                        saveImgToPhoto(imageView, list.get(position1));
                        return false;
                    })
                    .watch(position);
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    /**
     * 申请文件读写权限
     */
    private void registerPermission() {
        PermissionGen.with(this)
                .addRequestCode(Common.BASIC_PERMISSION_REQUEST_CODE)
                .permissions(Manifest.permission.WRITE_EXTERNAL_STORAGE
                        , Manifest.permission.READ_EXTERNAL_STORAGE)
                .request();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        PermissionGen.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }

    /**
     * 权限申请失败
     */
    @PermissionFail(requestCode = Common.BASIC_PERMISSION_REQUEST_CODE)
    public void openFail() {
        ToastUtils.show("权限获取失败，无法保存图片");
    }

    /**
     * 权限申请成功
     */
    @PermissionSuccess(requestCode = Common.BASIC_PERMISSION_REQUEST_CODE)
    public void openSuccess() {
        ImageUtil.saveMyBitmap(getActivity(), ((BitmapDrawable) saveImageView.getDrawable()).getBitmap(), "chat_" + System.currentTimeMillis() + ".jpg");
    }

    /**
     * 保存图片到相册
     */
    private void saveImgToPhoto(ImageView imageView, String url) {
        saveImageView = imageView;
        new Thread(() -> {
            Bitmap bitmap = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
            String result = QRCodeParseUtils.syncDecodeQRCode(bitmap);
            Message msg = new Message();
            msg.what = 0x03;
            Bundle bundle = new Bundle();
            bundle.putString("url", url);
            bundle.putString("qrcode", result);
            msg.obj = result;
            msg.setData(bundle);
            handler.sendMessage(msg);
        }).start();
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 0x02) {
                String result = msg.obj == null ? null : (String) msg.obj;
                LogUtils.d(result);
                if (EmptyUtils.isEmpty(result)) {
                    showError("未识别到二维码信息");
                    return;
                }
                if (result.contains("chat_number")) {
                    // 如果是多聊二维码，调用接口
                    mPresenter.getUserInfoByQrCode(getActivity(), result);
                } else if (TextHttpUtil.hasNetUrlHead(result)) {
                    // 网页链接，跳转到web界面
                    startActivity(new Intent(getActivity(), WebViewActivity.class)
                            .putExtra(WebViewActivity.INTENT_WEB_URL, result));
                } else {
                    // 都不是，直接展示结果
                    startActivity(new Intent(getActivity(), CaptureResultActivity.class)
                            .putExtra(CaptureResultActivity.INTENT_RESULT, result));
                }
            } else if (msg.what == 0x03) {
                Bundle bundle = msg.getData();
                String qrcode = bundle.getString("qrcode");
                List<String> list = new ArrayList<>();
                list.add("发送给朋友");
                list.add("收藏");
                list.add("保存到相册");
                if (EmptyUtils.isNotEmpty(qrcode)) {
                    list.add("识别图中二维码");
                }
                PublicRoundDialog roundDialog = new PublicRoundDialog(getActivity(), list, (pos, menu) -> {
                    switch (menu) {
                        case "发送给朋友":
                            collectImgPath = bundle.getString("url");
                            startActivity(new Intent(getActivity(), ChatShareUserActivity.class)
                                    .putExtra(ChatShareUserActivity.INTENT_FROM_TAG, 7));
                            break;

                        case "收藏":
                            collectImg(bundle.getString("url"));
                            break;
                        case "保存到相册":
                            registerPermission();
                            break;
                        case "识别图中二维码":
//                            new Thread(() -> {
//                                Bitmap bitmap = ((BitmapDrawable) saveImageView.getDrawable()).getBitmap();
//                                String result = QRCodeParseUtils.syncDecodeQRCode(bitmap);
//                                Message message = new Message();
//                                message.what = 0x02;
//                                message.obj = result;
//                                handler.sendMessage(message);
//                            }).start();
                            if (EmptyUtils.isEmpty(qrcode)) {
                                showError("未识别到二维码信息");
                                return;
                            }
                            if (qrcode.contains("chat_number")) {
                                // 如果是多聊二维码，调用接口
                                mPresenter.getUserInfoByQrCode(getActivity(), qrcode);
                            } else if (TextHttpUtil.hasNetUrlHead(qrcode)) {
                                // 网页链接，跳转到web界面
                                startActivity(new Intent(getActivity(), WebViewActivity.class)
                                        .putExtra(WebViewActivity.INTENT_WEB_URL, qrcode));
                            } else {
                                // 都不是，直接展示结果
                                startActivity(new Intent(getActivity(), CaptureResultActivity.class)
                                        .putExtra(CaptureResultActivity.INTENT_RESULT, qrcode));
                            }
                            break;
                    }
                });
                roundDialog.show();
            }
        }
    };

    /**
     * 收藏图片
     */
    private void collectImg(String url) {
        showLoading();
        DownLoadUtil.downLoadImg(url, new DownLoadUtil.OnDownLoadListener() {
            @Override
            public void success(String path) {
                hideLoading();
                mPresenter.upLoadImg(getActivity(), path);
            }

            @Override
            public void fail() {
                hideLoading();
                showError("图片下载失败");
            }
        });
    }

    /**
     * 添加头部布局
     */
    private void addHeaderView() {
        headerView = LayoutInflater.from(getActivity()).inflate(R.layout.layout_moment_header, null);
        tv_new_msg = headerView.findViewById(R.id.tv_new_msg);
        ivHead = headerView.findViewById(R.id.iv_head);
        tvNickName = headerView.findViewById(R.id.tv_nick_name);
        ivSex = headerView.findViewById(R.id.iv_sex);
        tvSign = headerView.findViewById(R.id.tv_sign);
        ivMomentBg = headerView.findViewById(R.id.iv_moment_bg);
        tv_new_msg.setVisibility(View.GONE);

        GlideUtils.loadImg(getActivity(), userInfoBean.getAvatar(), ivHead);
        if (EmptyUtils.isNotEmpty(userInfoBean.getBackimage())) {
            GlideUtils.loadImgAsCenter(getActivity(), userInfoBean.getBackimage(), ivMomentBg);
        }
        tvNickName.setText(userInfoBean.getNickname());
        tvSign.setText("个性签名：" + userInfoBean.getBio());
        if (UserInfoUtil.getUserSex().equals(SexEnum.SEX_GRIL)) {
            ivSex.setImageResource(R.mipmap.ic_icon_sex_gril);
            ivSex.setVisibility(View.VISIBLE);
        } else if (UserInfoUtil.getUserSex().equals(SexEnum.SEX_BOY)) {
            ivSex.setImageResource(R.mipmap.ic_icon_sex_boy);
            ivSex.setVisibility(View.VISIBLE);
        } else {
            ivSex.setVisibility(View.GONE);
        }

        momentAdapter.addHeaderView(headerView);
        momentAdapter.notifyDataSetChanged();
    }

    @OnClick({R.id.iv_back})
    public void viewOnClick(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                getActivity().finish();
                break;
        }
    }


    /**
     * 列表点击
     *
     * @param adapter
     * @param view
     * @param position
     */
    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        startActivity(new Intent(getActivity(), MomentInfoActivity.class)
                .putExtra(MomentInfoActivity.INTENT_MOMENT_ID, momentData.get(position).getDynamic_id()));
    }

    /**
     * 子控件点击
     *
     * @param adapter
     * @param view
     * @param position
     */
    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
        switch (view.getId()) {
            case R.id.iv_head: // 用户头像
                getActivity().finish();
                break;

            case R.id.tv_fabulous: // 点赞
                mPresenter.momentFabulous(getActivity(), momentData.get(position).getDynamic_id(), position);
                break;

            case R.id.tv_commont: // 评论
                startActivity(new Intent(getActivity(), MomentInfoActivity.class)
                        .putExtra(MomentInfoActivity.INTENT_MOMENT_ID, momentData.get(position).getDynamic_id()));
                break;
            case R.id.tv_content:// 文本点击
                if (EmptyUtils.isNotEmpty(momentData.get(position).getLinkurl())) {
                    startActivity(new Intent(getActivity(), WebViewActivity.class)
                            .putExtra(WebViewActivity.INTENT_WEB_URL, momentData.get(position).getLinkurl()));
                } else {
                    startActivity(new Intent(getActivity(), MomentInfoActivity.class)
                            .putExtra(MomentInfoActivity.INTENT_MOMENT_ID, momentData.get(position).getDynamic_id()));
                }
                break;
        }
    }

    /**
     * 数据获取成功
     *
     * @param data
     */
    @Override
    public void momentResult(List<MomentBean> data) {
        smartRefresh.finishRefresh();
        momentAdapter.loadMoreComplete();
        try {
            if (isRefresh) {
                momentData.clear();
            }
            momentData.addAll(data);
            if (data.size() < Common.PAGE_COUNT) {
                momentAdapter.loadMoreEnd();
            }
            if (momentData != null && momentData.size() > 0) {
                llNull.setVisibility(View.GONE);
            } else {
                llNull.setVisibility(View.VISIBLE);
            }
            momentAdapter.notifyDataSetChanged();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 加载失败
     */
    @Override
    public void onFail() {
        smartRefresh.finishRefresh();
        momentAdapter.loadMoreFail();
    }

    /**
     * 点赞成功
     */
    @Override
    public void fabulousSuccess(int pos) {
        if (momentData.get(pos).getGreatstate() == 0) {
            momentData.get(pos).setGreatstate(1);
            momentData.get(pos).setGreatcount(momentData.get(pos).getGreatcount() + 1);
        } else {
            momentData.get(pos).setGreatstate(0);
            momentData.get(pos).setGreatcount(momentData.get(pos).getGreatcount() - 1);
        }
        momentAdapter.notifyDataSetChanged();
    }

    /**
     * 图片上传成功
     *
     * @param data
     */
    @Override
    public void upLoadImgSuccess(UpLoadImgBean data) {
        // 图片上传成功，收藏图片
        mPresenter.addChatCollect(getActivity(), null, data.getUrl(), userInfoBean.getMember_id());
    }

    /**
     * 收藏成功
     */
    @Override
    public void collectSuccess() {
        showError("收藏成功");
    }

    /**
     * 根据二维码获取用户信息成功
     *
     * @param data
     */
    @Override
    public void userInfoResult(UserInfoBean data) {
        if (data.getMember_id() == UserInfoUtil.getUserId()) {
            startActivity(new Intent(getActivity(), MineUserInfoActivity.class));
            return;
        }
        if (data.getIs_buddy() == 1) {
            startActivity(new Intent(getActivity(), UserInfoActivity.class)
                    .putExtra(UserInfoActivity.INTENT_USER_ID, data.getMember_id()));
        } else {
            startActivity(new Intent(getActivity(), AddFriendActivity.class)
                    .putExtra(AddFriendActivity.INTENT_USER_ID, data.getMember_id())
                    .putExtra(AddFriendActivity.INTENT_TYPE, 2));
        }
    }

    /**
     * 加载更多
     */
    @Override
    public void onLoadMoreRequested() {
        page++;
        isRefresh = false;
        mPresenter.getMomentList(getActivity(), userInfoBean.getMember_id(), page);
    }

    /**
     * 刷新
     *
     * @param refreshLayout
     */
    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        page = 1;
        isRefresh = true;
        momentAdapter.setEnableLoadMore(true);
        mPresenter.getMomentList(getActivity(), userInfoBean.getMember_id(), page);
    }

    /**
     * 删除好友成功,退出界面
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void deleteFriendSuccess(DeleteFriendEvent event) {
        getActivity().finish();
    }


    /**
     * 用户备注名设置成功，更新列表相对应的昵称
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void setRemarkNameSuccess(UserRemarkEvent event) {
        for (int i = 0; i < momentData.size(); i++) {
            if (momentData.get(i).getMember_id() == event.getBean().getMember_id()) {
                momentData.get(i).setNickname(event.getBean().getRemarks_name());
            }
        }
        momentAdapter.notifyDataSetChanged();
    }

    /**
     * 转发选择好友返回
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void selectUserResult(ChatShareUserEvent event) {
        if (userInfoBean == null) {
            showError("暂未获取到用户信息，请稍后重试");
            return;
        }
        if (event.getTag() == 7) {
            showLoading();
            DownLoadUtil.downLoadImg(collectImgPath, new DownLoadUtil.OnDownLoadListener() {
                @Override
                public void success(String path) {
                    hideLoading();
                    ChatUtil.getInstance().sendImgMessage(getActivity(),path, event.getBean().getHxusername(), ChatConstant.CHATTYPE_SINGLE,
                            event.getBean().getMember_id(), EmptyUtils.isEmpty(event.getBean().getRemarks_name()) ? event.getBean().getNickname() :
                                    event.getBean().getRemarks_name(), null);
                    showError("发送成功");
                }

                @Override
                public void fail() {
                    hideLoading();
                    showError("图片下载失败");
                }
            });
        }
    }
}
